package com.sywb.chuangyebao.contract;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Comment;
import com.sywb.chuangyebao.bean.MyComment;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.NewsDetailActivity;
import com.sywb.chuangyebao.view.TrainMediaDetailActivity;
import com.sywb.chuangyebao.view.VideoDetailActivity;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.TimeUtils;

import java.util.List;

/**
 * Created by duxl on 2018/5/4.
 */

public interface MyCommentContract {

    enum FLAG_DIALOG {
        DEL_COMMENT
    }

    interface MyCommentView extends BaseRefreshContract.View {
        void showConfirmDialog(FLAG_DIALOG flag, String msg, Object... args);
    }

    class Presenter extends BaseRefreshContract.Presenter<MyCommentView> {

        private CommentAdapter recyclerAdapter;
        private int pageNumber = 1;

        @Override
        public void onStart() {
            super.onStart();
            recyclerAdapter = new CommentAdapter(mContext);
            setRecyclerAdapter(recyclerAdapter);
            recyclerAdapter.setPageSize(1);

            initData();
        }

        @Override
        public void initData() {
            super.initData();
            getListData();
        }

        @Override
        public void onStartRefresh() {
            Logger.e("MyCommentContract onStartRefresh");
            pageNumber = 1;
            getListData();
        }

        @Override
        public void onStartLoadMore() {
            Logger.e("MyCommentContract onStartLoadMore");
            pageNumber++;
            getListData();
        }

        public void getListData() {
            HttpUtils.getMyComment(pageNumber, new HttpCallback<List<MyComment>>() {
                @Override
                public void onSuccess(List<MyComment> myComments) {
                    if (pageNumber == 1) {
                        onEndRefresh();
//                        if (myComments != null && myComments.size() > 0) {
//                            recyclerAdapter.setFooterView(R.layout.layout_footer);
//                        } else {
//                            recyclerAdapter.setFooterView(null);
//                        }
                        recyclerAdapter.setFooterView(null);
                        recyclerAdapter.clearDatas();
                    } else {
                        if (myComments != null && myComments.size() > 0) {
                            recyclerAdapter.setFooterView(R.layout.layout_footer);
                        } else {
                            recyclerAdapter.setFooterView(null);
                        }
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(myComments);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    if (pageNumber == 1) {
                        onEndRefresh();
                    } else {
                        onEndLoadMore();
                    }
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData();
                }
            });
        }


        class CommentAdapter extends BaseRecyclerAdapter<MyComment> {

            public CommentAdapter(Context context) {
                super(context, R.layout.item_my_comment);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int i, MyComment myComment) {
                viewHolderHelper.setItemChildClickListener(R.id.ll_original_item_my_comment);
                viewHolderHelper.setItemChildClickListener(R.id.iv_del_item_my_comment);

                RichTextView richTextView = viewHolderHelper.getView(R.id.tv_content_item_my_comment);
                richTextView.setDeviationDP(R.dimen.dp_30);
                richTextView.setDataPostion(i);
                richTextView.setExpandView(true);
                richTextView.setExpandedOpen(false);
                richTextView.setRichText(myComment.content, null);

                viewHolderHelper.setText(R.id.tv_original_item_my_comment, myComment.topic.title);

                ImageView ivMediaType = viewHolderHelper.getView(R.id.iv_media_type_item_my_comment);
                ivMediaType.setVisibility(View.GONE);

                if (TextUtils.isEmpty(myComment.topic.pic)) {
                    viewHolderHelper.setVisibility(R.id.rl_media_item_my_comment, View.GONE);
                } else {
                    ImageView img = viewHolderHelper.getView(R.id.iv_img_item_my_comment);
                    GlideUtils.getNormalIamgeToUrl(mActivity, myComment.topic.pic, img, R.drawable.news_pic_default);

                    if ("video".equals(myComment.topic.topic_type)) {
                        ivMediaType.setImageResource(R.drawable.icon_media_video);
                        ivMediaType.setVisibility(View.VISIBLE);

                    } else if ("audio".equals(myComment.topic.topic_type)) {
                        ivMediaType.setImageResource(R.drawable.icon_media_audio);
                        ivMediaType.setVisibility(View.VISIBLE);
                    }
                }

                viewHolderHelper.setText(R.id.tv_time_item_my_comment, TimeUtils.transformDate10(myComment.date_time));
            }
        }

        @Override
        public void onRecyclerItemChildClick(View view, int position) {
            MyComment myComment = recyclerAdapter.getItem(position);

            int topicId = myComment.topic.topic_id;
            if (view.getId() == R.id.ll_original_item_my_comment) { // 跳转到评论处（到了对应详情页面自动弹出评论Dialog）

                if (myComment.topic.getType() == 0) {
                    mView.advance(NewsDetailActivity.class, topicId);

                } else if (myComment.topic.getType() == 1) {
                    mView.advance(VideoDetailActivity.class, topicId);

                } else if (myComment.topic.getType() == 2) {
                    mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.video_detail), String.valueOf(topicId));

                } else if (myComment.topic.getType() == 3) {
                    mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.audio_detail), String.valueOf(topicId));

                } else if (myComment.topic.getType() == 4) {
                    mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.special_detail), String.valueOf(topicId));
                }

            } else if (view.getId() == R.id.iv_del_item_my_comment) { // 删除我的评论
                String msg = null;
                if (myComment.getType() == 0) {
                    msg = mActivity.getResources().getString(R.string.comment_del_hint);
                } else if (myComment.getType() == 1) {
                    msg = mActivity.getResources().getString(R.string.comment_reply_del_hint);
                }

                if (!TextUtils.isEmpty(msg)) {
                    mView.showConfirmDialog(FLAG_DIALOG.DEL_COMMENT, msg, myComment, position);
                }
            }
        }

        @Override
        public void onRecyclerItemClick(int position) { // 评论被点击，跳转到评论回复页面
            MyComment myComment = recyclerAdapter.getItem(position).getCommentData();
            if (myComment == null) {
                return;
            }

            // 构造Comment对象
            Comment comment = new Comment();
            comment.comment_id = myComment.id;
            comment.content = myComment.content;
            comment.thumb_count = myComment.thumb_count;
            comment.is_thumb = myComment.is_thumb;
            comment.date_time = myComment.date_time;
            String openID = SharedUtils.getString(Constants.USEROPENID, "");
            UserInfo userInfo = DbManager.getInstance().queryById(openID, UserInfo.class);
            comment.from_user = MyComment.convertUserInfoToNewsOwner(userInfo);
            comment.from_uid = comment.from_user.uid;

            int topicId = myComment.topic.topic_id;
            if (myComment.topic.getType() == 0) {
                mView.advance(NewsDetailActivity.class, topicId, comment);

            } else if (myComment.topic.getType() == 1) {
                mView.advance(VideoDetailActivity.class, topicId, 0, 0, comment);

            } else if (myComment.topic.getType() == 2) {
                mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.video_detail), String.valueOf(topicId), comment);

            } else if (myComment.topic.getType() == 3) {
                mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.audio_detail), String.valueOf(topicId), comment);

            } else if (myComment.topic.getType() == 4) {
                mView.advance(TrainMediaDetailActivity.class, mActivity.getString(R.string.special_detail), String.valueOf(topicId), comment);
            }
        }

        /**
         * 提示弹框点击确认后调用此方法
         *
         * @param flag
         * @param args
         */
        public void afterConfirmDialog(FLAG_DIALOG flag, final Object... args) {
            if (flag == FLAG_DIALOG.DEL_COMMENT) {
                MyComment myComment = (MyComment) args[0];
                delComment(myComment, (int) args[1]);
            }
        }

        /**
         * 删除评论或回复
         *
         * @param comment 评论ID
         */
        public void delComment(MyComment comment, int position) {
            if (!Utils.checkIsNext(mView.getMyFragmentManager())) {
                return;
            }
            if (comment.getType() == 0) {
                HttpUtils.delComment(comment.id, getHttpCallback(position));
            } else if (comment.getType() == 1) {
                HttpUtils.delCommentReply(comment.id, getHttpCallback(position));
            }
        }

        /**
         * 删除评论和回复共用一个回调处理
         *
         * @param position
         * @return
         */
        private HttpCallback getHttpCallback(int position) {
            return new HttpCallback<String>(position) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(String result) {
                    int position = ((Integer) data).intValue();
                    recyclerAdapter.getDatas().remove(position);
                    recyclerAdapter.notifyDataSetChanged();
                    if (recyclerAdapter.getDatas() == null && recyclerAdapter.getDatas().isEmpty()) {
                        onStartRefresh();
                    }
                    showMessage(R.string.comment_del_success);
                    RxBus.get().post(Constants.COMMENT_REPLY_CHANGE, "");
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            };
        }
    }
}
